package com.booleansoft.redirect;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hsqldb.Server;

import com.booleansoft.RedirectServer;
import com.booleansoft.model.redirect.Transmit;
import com.booleansoft.redirect.service.SimpleobjectService;
import com.booleansoft.util.NumberHelper;
import com.booleansoft.util.PortHelper;
import com.booleansoft.util.SqlHelper;

public class DirectContext {
	private static volatile Map<String,Transmit> map=null;
	SimpleobjectService simpleobjectService=new SimpleobjectService();
	private static Server server = new Server();
	public static final String dbname="redirect";
	private int []fromport;
	private int cmdport;
	private static int hsqlport=2000;
	public static   String ROOT=null;
	public int[] getFromport() {
		return fromport;
	}
	public int getCmdport() {
		return cmdport;
	}
	private DirectContext(){
		loadConfig();
		startServer();
	}
	public void loadConfig(){
		ROOT=RedirectServer.root;
		File confile=new File(ROOT+"conf"+File.separator+"config.httf");
		BufferedReader in=null;
		Map hash=new Hashtable();
		try {
			in=new BufferedReader(new FileReader(confile));
			String str=null;
			while((str=in.readLine())!=null){
				int i=str.lastIndexOf("=");
				hash.put(str.substring(0,i), str.substring(i+1));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {}
			}
		}
		String fp=(String)hash.get("fromport");
		String pfs[]=fp.split("\\s*,\\s*");
		fromport=new int[pfs.length];
		int i=0;
		for(String s:pfs){
			fromport[i++]=Integer.parseInt(s);
		}
		cmdport=Integer.parseInt((String)hash.get("cmdport"));
		hsqlport=NumberHelper.getIntValue(hash.get("hsqlport"));
		if(hsqlport==0){
			hsqlport=PortHelper.getAvaliPort();
		}else if(PortHelper.isOn(hsqlport)>0){
			hsqlport=PortHelper.getAvaliPort();
			System.out.println("端口["+hsqlport+"]被占用,切换到["+hsqlport+"]");
		}
	}
	private void startServer(){
		server.setPort(hsqlport);
		server.setDatabaseName(0, dbname);
		server.setDatabasePath(0, (DirectContext.ROOT+"datas"+File.separator+"db"+File.separator+ dbname).replace(File.separator, "/"));
		server.setSilent(true);
		server.start();
		System.out.println("hsqldb start@port="+hsqlport);
	}
	public  void loadMap(){
		map=new Hashtable<String,Transmit>();
		try {
			SqlHelper helper=SqlHelper.getInstance();
			List list=helper.getValues("select * from transmit");
			for(int i=0;i<list.size();i++){
				Map datamap=(Map)list.get(i);
				Transmit t=new Transmit().fromMap(datamap);
				map.put(t.getDomain().toLowerCase(), t);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static DirectContext instance=new DirectContext();
	public static DirectContext getInstance() {
		return instance;
	}
	private Transmit write(String domain,String ip,int port,String discriber){
		Transmit t=new Transmit();
		SqlHelper helper=SqlHelper.getInstance();
		Map map=helper.getQueryMap("select * from transmit where domain='"+domain+"'");
		t.fromMap(map);
		t.setDomain(domain);
		t.setIp(ip);
		t.setPort(port);
		t.setDiscribe(discriber);
		t.setCreatetime(new Date());
		simpleobjectService.save(t);
		getMap().put(domain, t);
		return t;
	}
	
	private void addOne(String doman,String addr1,int port,String discriber){
		doman=doman.toLowerCase();
		write(doman,addr1,port,discriber);
	}
	public void add(String doman,String addr1,int port,String discriber){
		if(doman.equals("localhost")||doman.equals("127.0.0.1")){
			addOne("localhost",addr1,port,discriber);
			addOne("127.0.0.1",addr1,port,discriber);
			addOne("0:0:0:0:0:0:0:1",addr1,port,discriber);
		}else{
			addOne(doman,addr1,port,discriber);
		}
	}
	public void remove(String doman){
		getMap().remove(doman);
		SqlHelper helper=SqlHelper.getInstance();
		helper.execute("delete from transmit where domain='"+doman+"'");
	}
	public void removeAll(){
		getMap().clear();
		SqlHelper helper=SqlHelper.getInstance();
		helper.execute("delete from transmit ");
	}
	public Transmit get(String doman){
		if(doman==null){
			return null;
		}
		doman=doman.toLowerCase();
		Transmit redi=(Transmit) getMap().get(doman);
		return redi;
	}
	public String getAll(){
		StringBuffer sb=new StringBuffer();
		Iterator iterator=getMap().keySet().iterator();
		while(iterator.hasNext()){
			String key=(String)iterator.next();
			Transmit redi=(Transmit) getMap().get(key);
			sb.append(redi.toString());
			sb.append("\r\n");
		}
		return sb.toString().replaceFirst("\r\n$", "");
	}
	public static void  main(String args[]){
//			DirectContext.getInstance().add("127.0.0.1",
//					"localhost", 8080, "本地系统");
			 
	}
	public static int getHsqlport() {
		return hsqlport;
	}
	public Map<String, Transmit> getMap() {
		if(map==null){
			synchronized(this){
				if(map==null){
					loadMap();
				}
			}
		}
		return map;
	}
}
